package my.codeandroid.antollroid;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

//Ref: http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/
public class DatabaseHelper extends SQLiteOpenHelper {
	// Default DB path http://developer.android.com/guide/topics/data/data-storage.html#db
	private static final String DB_NAME = "antollroid_db";
	private final Context context;
	
	public DatabaseHelper(Context context) {
		super(context, DB_NAME, null, 1);		
		this.context = context;
		
		String path = context.getDatabasePath(DB_NAME).getAbsolutePath();
		SQLiteDatabase db = null;
		try {
			db = SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.OPEN_READONLY);
		} catch (SQLiteException e) { // DB not found
			/* The getReadableDatabase and close actions is mandatory.
			 * It will create the necessary folders and files.
			 */
			db = getReadableDatabase();
			db.close();
			// Copy DB from asset folder.
			copyDatabase(path);
		}
		
		if (db != null) {
			db.close();
		}
	}
	
	private void copyDatabase(String path) {
		try {
			InputStream inputStream = context.getAssets().open(DB_NAME);
			OutputStream outputStream = new FileOutputStream(path);
			
			// Transfer bytes from the inputfile to the outputfile
	    	byte[] buffer = new byte[1024];
	    	int length;
	    	while ((length = inputStream.read(buffer))>0){
	    		outputStream.write(buffer, 0, length);
	    	}
	    	
	    	// Close the streams
	    	outputStream.flush();
	    	outputStream.close();
	    	inputStream.close();
		} catch (FileNotFoundException exception) {
			Log.e("Antollroid", "DatabaseHelper: Cannot write data to application DB folder.");
			return;
		} catch (IOException exception) {
			Log.e("Antollroid", "DatabaseHelper: Cannot read DB file from asset folder.");
			return;
		} 
		
		Log.d("Antollroid", "DatabaseHelper: Successfully copied DB from asset folder to application folder.");
	}
	
	@Override
	public void onCreate(SQLiteDatabase db) {		
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
	}

}